﻿//页面加载
$(document).ready(function () {
    $("#btnSave").bind("click", btnSave_click);
    $("#btnCancel").bind("click", btnCancel_click);
   // $("#btnSend").bind("click", btnSend_click);
   // $("#txtCardCode").bind("input propertychange", txtCardCode_change);
    bindOrderDetials();

    $("#txtpwd").focus();
})

function bindOrderDetials() {
    //显示订单详细
    var v_orderId = $("#orderId").val();
    $.post("/Order/GetOrder", { Id: v_orderId }, function (result) {
        $("#txtCardCode").val(result.data.Buyer);
        //显示用户相关性信息
        txtCardCode_change();
        ShowShoppingCard(result);
    }, "json");

}

//给用户发送验证码
function btnSend_click() {
    var v_openId = $("#openid").val();
    if (v_openId == "") {
        alert("此卡未关注公众号或未绑定，不能完成支付！");
        return;
    }
    var $table = $("#TableList");
    var v_count = $table.find(".contentRow").length;
    if (v_count == 0) {
        alert("请先选择产品！");
        return;
    }
    var v_cardCode = $("#txtCardCode").val();
    if (v_cardCode == "") {
        alert("请输入卡号！");
        return;
    }
    var v_orderId = $("#orderId").val();
    $("#codeMsg").html("");
    $.post("/Order/SendValidateCode", { orderId: v_orderId, openid: v_openId, cardCode: v_cardCode }, function (result) {
        if (result.code == "OK") {
            $("#codeMsg").html("验证码发送成功!");
            var endTime = result.data.EndDateString;
            $("#lxftime").attr("data-endtime", endTime);
            lxfEndtime();  //轮询倒计时
            CheckPaied();
        }
        else {
            $("#codeMsg").html("发送失败，请稍后重试");
        }
    }, "json");

}

//验证码倒计时
function lxfEndtime() {
    $("#lxftime").each(function () {
        var lxfday = $(this).attr("data-lxfday");//用来判断是否显示天数的变量
        var endtime = new Date($(this).attr("data-endtime")).getTime();//取结束日期(毫秒值)
        var nowtime = new Date().getTime();        //今天的日期(毫秒值)
        var youtime = endtime - nowtime;//还有多久(毫秒值)
        var seconds = youtime / 1000;
        var minutes = Math.floor(seconds / 60);
        var hours = Math.floor(minutes / 60);
        var days = Math.floor(hours / 24);
        var CDay = days;
        var CHour = hours % 24;
        var CMinute = minutes % 60;
        var CSecond = Math.floor(seconds % 60);//"%"是取余运算，可以理解为60进一后取余数，然后只要余数。
        if (endtime <= nowtime) {
            $(this).html("已过期")//如果结束日期小于当前日期就提示过期啦
        } else {
            if ($(this).attr("data-lxfday") == "no") {
                $(this).html("<strong>剩余时间：</strong><span>" + CHour + "</span>时<span>" + CMinute + "</span>分<span>" + CSecond + "</span>秒");          //输出没有天数的数据
            } else {
                $(this).html("<strong>剩余时间：</strong><span>" + days + "</span><em>天</em><span>" + CHour + "</span><em>时</em><span>" + CMinute + "</span><em>分</em><span>" + CSecond + "</span><em>秒</em>");          //输出有天数的数据
            }
        }
    });
    setTimeout("lxfEndtime()", 1000);
};

//检查支付情况
function CheckPaied() {
    setInterval(chat, "5000"); //5秒轮询一次，看是否支付完成
}
function chat() {

    //关闭ajax 遮罩模式
    g_IsOpenAjax = false;

    v_orderId = $("#orderId").val();
    $.post("/Order/FinishOrder", { orderId: v_orderId }, function (result) {
        if (result.code == "OK") {
            $("#codeMsg").html("支付成功!");
            window.location.href = "/Order/index";
        }
        else {
            $("#codeMsg").html("等待回复验证码...");
        }
    }, "json");
}

//自动获取卡号用户信息
function txtCardCode_change() {
    $("#cardMsg").html("");
    $("#balance").html("");
    $("#wxUser").html("");
    $("#openid").val("");

    v_cardCode = $("#txtCardCode").val();

    $.post("/Order/GetCardInfo", { cardCode: v_cardCode }, function (result) {
        if (result.code == 1) {
            $("#cardMsg").html(result.msg);
        }
        else if (result.code == 2) {
            $("#cardMsg").html(result.card.RealName);
            $("#balance").html("￥" + result.card.Balance);
            $("#wxUser").html(result.user.NickName);
            $("#openid").val(result.user.OpenId);
        }
        else if (result.code == 3) {
            $("#cardMsg").html(result.card.RealName);
            $("#balance").html("￥" + result.card.Balance);
            $("#wxUser").html("此卡未关注公众号或未绑定！");
        }
    }, "json");
}

function btnAdd_click() {
    var v_ProductId = $("#Products").val();
    if (v_ProductId == 0) {
        alert("请选择一个产品");
        return;
    }
    var v_cardCode = $("#txtCardCode").val();
    if (v_cardCode == "") {
        alert("请输入购买人卡号");
        return;
    }
    var v_quantity = $("#txtQuantity").val();
    $.post("/Order/AddToShoppingCart", { cardCode: v_cardCode, productId: v_ProductId, quantity: v_quantity }, function (result) {
        ShowShoppingCard(result);
    }, "json");

}

function ShowShoppingCard(result) {
    var $table = $("#TableList");
    var $template = $("#template");
    $table.find(".contentRow").remove();
    $.each(result.data.OrderItems, function (i, n) {
        var row = $template.clone();
        row.css("display", "");
        //数据项
        row.find("#td_checkbox").html("<input type='checkbox' name='checkbox'  class='chk' value='" + n.Pro_ID + "'/>");
        row.find("#td_Image").html("<img class='proImage mt5 mb5' src='" + n.Image + "'></img>");
        row.find("#td_ProductName").html(n.ProductName);
        row.find("#td_Price").html("￥" + n.Price);
        row.find("#td_Quantity").html(n.Quantity);
        row.find("#td_Discount").html(n.Discount);
        row.find("#td_BuyPrice").html("￥" + n.BuyPrice);
        row.find("#td_Total").html("￥" + n.Total);
        //操作
        //row.find("#btnSetMenu").bind("click", { ID: n.AID }, btnSetMenu_click);
        // row.find("#btnEdit").bind("click", { ID: n.AID }, btnEdit_click);
        row.find("#btnDelete").bind("click", { ID: n.Pro_ID }, btnDelete_click);
        row.attr("class", "contentRow t_c");
        row.appendTo($table);
    });

    // 订单总价：
    $("#orderTotal").html(result.orderTotal);
}

//<td id="td_ProductName">@item.ProductName</td>
//删除单项
function btnDelete_click(e) {
    var Id = e.data.ID;
    $.post("/Order/Remove", { productId: Id }, function (result) {
        ShowShoppingCard(result);
    }, "json");

}

function btnMinus_click() {
    var quantity = $("#txtQuantity");
    var curValue = parseInt(quantity.val()) - 1;
    if (curValue < 1) {
        curValue = 1;
    }
    quantity.val(curValue);
}

function btnPlus_click() {
    var quantity = $("#txtQuantity");
    var curValue = parseInt(quantity.val()) + 1;
    quantity.val(curValue);
}

//获取产品列表
function GetProducts_change() {
    var v_select = $(this).val();

    $.post("/Order/GetProductsByType", { selectTypeId: v_select }, function (result) {
        var ddlHtml = "<option value='0'>请选择</option>";
        $.each(result.data, function (i, item) {
            var item = "<option value='" + item.AID + "'>" + item.Name + "</option>";
            ddlHtml += item;
        })
        $("#Products").html(ddlHtml);
    }, "json");
}

function btnSave_click() {
    var v_pwd = $("#txtpwd").val();
    if (v_pwd == "")
    {
        $("#dvMsg").html("密码不能为空!");
        return;
    }
    var v_orderid=$("#orderId").val();
    //异步提交表单,表单中input元素必须设置name 属性
    $.post("/Order/PayOrder", { orderId: v_orderid, pwd: v_pwd }, function (result) {
        if (result.code == "OK") {
            alert("数据保存成功!");
            window.location.href = "/Order/Index";
        }
        else {
            $("#dvMsg").html(result.msg);
        }
    });
}

function btnCancel_click() {
    window.location.href = "/Order/Index";
}

//时间字符串截取
function CutString(str, index, length) {
    if (str != null && str != undefined) {
        if (str.length >= length) {
            if (length > 10) {
                var str1 = str.substring(index, length);
                return str1.replace("T", " ");
            }
            else {
                return str.substring(index, length);
            }
        }
        else {
            return str;
        }
    }
    else {
        return "";
    }
}